package com.logistics.security;

import io.jsonwebtoken.*;
import io.jsonwebtoken.security.Keys;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.crypto.SecretKey;
import java.nio.charset.StandardCharsets;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * JWT Token 工具类
 */
@Component
public class JwtTokenProvider {
    
    @Value("${jwt.secret}")
    private String secret;
    
    @Value("${jwt.expiration}")
    private Long expiration;
    
    /**
     * 生成 Token
     */
    public String generateToken(Long userId, Long tenantId, Long siteId, String username, String role) {
        return generateToken(userId, tenantId, siteId, username, role, null);
    }

    /**
     * 生成 Token（包含权限列表）
     */
    public String generateToken(Long userId, Long tenantId, Long siteId, String username, String role, java.util.List<String> permissions) {
        Date now = new Date();
        Date expiryDate = new Date(now.getTime() + expiration * 1000);
        
        SecretKey key = Keys.hmacShaKeyFor(secret.getBytes(StandardCharsets.UTF_8));
        
        io.jsonwebtoken.JwtBuilder builder = Jwts.builder()
                .claim("userId", userId)
                .claim("tenantId", tenantId)
                .claim("siteId", siteId)
                .claim("username", username)
                .claim("role", role)
                .subject(username)
                .issuedAt(now)
                .expiration(expiryDate)
                .signWith(key);

        if (permissions != null) {
            builder.claim("perms", permissions);
        }

        return builder.compact();
    }
    
    /**
     * 从 Token 中获取用户ID
     */
    public Long getUserIdFromToken(String token) {
        Claims claims = getClaimsFromToken(token);
        return claims.get("userId", Long.class);
    }
    
    /**
     * 从 Token 中获取租户ID
     */
    public Long getTenantIdFromToken(String token) {
        Claims claims = getClaimsFromToken(token);
        return claims.get("tenantId", Long.class);
    }
    
    /**
     * 从 Token 中获取用户名
     */
    public String getUsernameFromToken(String token) {
        Claims claims = getClaimsFromToken(token);
        return claims.getSubject();
    }
    
    /**
     * 从 Token 中获取角色
     */
    public String getRoleFromToken(String token) {
        Claims claims = getClaimsFromToken(token);
        return claims.get("role", String.class);
    }
    
    /**
     * 从 Token 中获取权限列表
     */
    @SuppressWarnings("unchecked")
    public java.util.List<String> getPermissionsFromToken(String token) {
        Claims claims = getClaimsFromToken(token);
        Object perms = claims.get("perms");
        if (perms instanceof java.util.List<?>) {
            java.util.List<?> raw = (java.util.List<?>) perms;
            java.util.List<String> result = new java.util.ArrayList<>();
            for (Object o : raw) {
                if (o != null) result.add(String.valueOf(o));
            }
            return result;
        }
        return null;
    }
    
    /**
     * 从 Token 中获取站点ID
     */
    public Long getSiteIdFromToken(String token) {
        Claims claims = getClaimsFromToken(token);
        Object siteIdObj = claims.get("siteId");
        if (siteIdObj == null) {
            return null;
        }
        if (siteIdObj instanceof Number) {
            return ((Number) siteIdObj).longValue();
        }
        return null;
    }
    
    /**
     * 验证 Token 是否有效
     */
    public boolean validateToken(String token) {
        try {
            SecretKey key = Keys.hmacShaKeyFor(secret.getBytes(StandardCharsets.UTF_8));
            Jwts.parser()
                .verifyWith(key)
                .build()
                .parseSignedClaims(token);
            return true;
        } catch (JwtException | IllegalArgumentException e) {
            return false;
        }
    }
    
    /**
     * 获取 Claims
     */
    private Claims getClaimsFromToken(String token) {
        SecretKey key = Keys.hmacShaKeyFor(secret.getBytes(StandardCharsets.UTF_8));
        return Jwts.parser()
                .verifyWith(key)
                .build()
                .parseSignedClaims(token)
                .getPayload();
    }
}

